<template>
  <div class="container" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="searchBox searchInputWidth"
        style="padding-bottom: 0; position: relative"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="企业名称" class="row-padding-bottom">
              <el-input
                v-model="filterField.companyName"
                placeholder="请输入企业名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="巡查日期" class="row-padding-bottom">
              <timeSelection
                @getStartTimeValue="getStartTimeValue"
                @getEndTimeValue="getEndTimeValue"
              ></timeSelection>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="任务编号" class="row-padding-bottom">
                <el-input
                  v-model="filterField.jobNumber"
                  placeholder="请输入任务编号"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="整改状态" class="row-padding-bottom">
                <el-select
                  v-model="filterField.rectificationStatus"
                  filterable
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in statusOption"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="延期整改" class="row-padding-bottom">
                <el-select
                  v-model="filterField.isDelay"
                  filterable
                  placeholder="请选择"
                  clearable
                  :popper-append-to-body="false"
                >
                  <el-option
                    v-for="item in isDelayOption"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item label="">
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <exportBtn
              v-if="!isShowAdd"
              :dataLen="tableList.length"
              :filterField="filterField"
              :api="api"
            ></exportBtn>
          </el-form-item>
          <!-- <el-form-item>
                    <exportBtn :dataLen="tableList.length" :filterField="filterField" :api="api"></exportBtn>
                    </el-form-item> -->
          <!-- <el-form-item>
                        <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button>
                    </el-form-item> -->
          <!-- <el-form-item>
                        <el-button v-if="isShowAdd" class="commonBut saveBtn funComBut" icon="iconfont icontianjia" @click="toAddPatro">
                            <span class="opetareText">创建巡查</span>
                        </el-button>
                    </el-form-item> -->
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            :api="api"
          ></exportBtn>
          <el-button
            class="commonBut saveBtn funComBut"
            icon="iconfont icontianjia"
            @click="toAddPatro"
          >
            <span class="opetareText">创建巡查</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          @sort-change="sortChange"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="80px"
          ></el-table-column>
          <!-- <el-table-column prop="companyName" label="企业名称" :formatter=formatTd></el-table-column> -->
          <el-table-column label="企业名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.companyName"
                :columnName="'companyName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="inspectionDate"
            label="巡查日期"
            sortable="custom"
            min-width="180px"
            :formatter="formatTd"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="rectificationStatusDesc"
            label="整改状态"
            :formatter="formatTd"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="jobNumber"
            label="任务编号"
            :formatter="formatTd"
            min-width="180"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" fixed="right" width="230">
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="isShowDetail"
                @click="seeDetail(scope.row)"
                >详情</el-link
              >
              <el-link
                v-if="
                  scope.row.rectificationStatus ==
                    'NO_RECTIFICATION_REQUIRED' && isShowUpdate
                "
                type="primary"
                @click="toUpdate(scope.row)"
                >修改</el-link
              >
              <el-link
                v-if="
                  scope.row.rectificationStatus == 'PENDING_RECTIFICATION' &&
                  isShowUpdate
                "
                type="primary"
                @click="toDispose(scope.row)"
                >处理</el-link
              >
              <el-link
                v-if="
                  scope.row.rectificationStatus == 'IN_PROCESS_RECTIFICATION' &&
                  isShowUpdate
                "
                type="primary"
                @click="toRectify(scope.row)"
                >完成整改</el-link
              >
              <el-link
                v-if="isShowDelete"
                type="primary"
                @click="deletePatrol(scope.$index, scope.row)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      title="完成整改"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="420px"
      class="tipDialog"
      :modal-append-to-body="false"
    >
      <el-form :model="dialogForm" ref="dialogForm">
        <el-form-item label="是否延期" :label-width="formLabelWidth">
          <el-select
            v-model="dialogForm.isDelay"
            placeholder="请选择"
            class="selectWidth"
            clearable
            :popper-append-to-body="false"
          >
            <el-option label="未延期" value="1"></el-option>
            <el-option label="已延期" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="toSave"
          class="save"
          :loading="canSave"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'patrolListFJ',
  props: ['domain', 'taskType'],
  data() {
    return {
      curPageNo: 1,
      total: 4,
      pageSizeNumber: 20,
      statusOption: [],
      isDelayOption: [
        {
          code: '0',
          name: '是',
        },
        {
          code: '1',
          name: '否',
        },
      ],
      //表格数据
      tableList: [],
      advanced: false,
      requestUrl: 'api-gov/ipqccompany/findcompanypatrol',
      areaId: '', //区域
      //搜索条件
      filterField: {
        companyName: '',
        startDateStr: '',
        endDateStr: '',
        jobNumber: '',
        rectificationStatus: '',
        isDelay: '',
      },
      pageSize: 20,
      pageNo: 1,
      isShow: false, //列表加载
      isShowDetail: '',
      isShowExprot: '',
      loading: true,
      dialogVisible: false,
      formLabelWidth: '80px',
      dialogForm: {
        id: '',
        isDelay: '',
      },
      canSave: false,
      isShowAdd: false,
      isShowUpdate: false,
      isShowDelete: false,
      isShowDetail: false,
      hiddleToolBar: false,
      tableHeight: null,
      api: '',
    }
  },
  created() {
    //整改状态
    this.getStateOption()
    //判断日常还是专项巡查
    if (this.taskType == 'SPECIAL') {
      this.filterField.taskType = 'SPECIAL'
      this.isShowAdd =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolListSpecial:add') > -1
      this.isShowUpdate =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolListSpecial:update') >
        -1
      this.isShowDelete =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolListSpecial:delete') >
        -1
      this.isShowDetail =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolListSpecial:detail') >
        -1
    } else {
      this.filterField.taskType = 'DAILY'
      this.isShowAdd =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolList:add') > -1
      this.isShowUpdate =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolList:update') > -1
      this.isShowDelete =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolList:delete') > -1
      this.isShowDetail =
        this.$store.state.buttonLimitsArr.indexOf('mPatrolList:detail') > -1
    }
    this.getApi()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }
      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  activated() {
    // this.getEventType();
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getStateOption() {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqccompany/ipqcRectificationStatus',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.statusOption = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    seeDetail(row) {
      this.$router.push({
        path: '/home/patrol/patrolDetail',
        name: 'patrolDetail',
        query: {
          domain: this.domain,
          patroId: row.id, //巡查id
          taskType: this.taskType,
        },
      })
      this.tabChoose()
    },
    toUpdate(row) {
      this.$router.push({
        path: '/home/patrol/patrolEdit',
        name: 'patrolEdit',
        query: {
          domain: this.domain,
          patroId: row.id, //巡查id
          taskType: this.taskType,
        },
      })
      this.tabChoose()
    },
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValue(val) {
      if (val) {
        this.filterField.startDateStr = val
      } else {
        this.filterField.startDateStr = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValue(val) {
      if (val) {
        this.filterField.endDateStr = val
      } else {
        this.filterField.endDateStr = ''
      }
    },
    //创建巡查
    toAddPatro() {
      this.$router.push({
        path: '/home/patrol/patrolAddFirst',
        name: 'patrolAddFirst',
        query: {
          domain: this.domain,
          taskType: this.taskType,
        },
      })
      this.tabChoose()
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //删除
    deletePatrol(index, row) {
      this.$confirm('确认删除该巡查数据吗?', '提示', {
        cancelButtonClass: 'btn-custom-cancel',
        type: 'warning',
      })
        .then(() => {
          this.toDel(row.id)
        })
        .catch(() => {
          this.$message.error('删除失败')
        })
    },
    toDel(id) {
      this.axios({
        method: 'post',
        url: 'api-gov/ipqccompany/delIpqcCompany',
        data: {
          id: id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              //删除成功刷新列表
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    /**处理*/
    toDispose(row) {
      this.$router.push({
        path: '/home/patrol/patrolDetail',
        name: 'patrolDetail',
        query: {
          domain: this.domain,
          patroId: row.id,
          taskType: this.taskType,
          dispose: 'dispose',
        },
      })
      this.tabChoose()
    },
    /**完成整改*/
    toRectify(row) {
      this.dialogForm.id = row.id
      this.dialogVisible = true
    },
    toSave() {
      let url
      if (this.domain === 'JZ') {
        url = 'api-gov/ipqcproject/rectifyOverIpqcProject'
      } else {
        url = 'api-gov/ipqccompany/rectifyOverIpqcCompany'
      }
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.canSave = true
          this.axios({
            method: 'post',
            url: url,
            data: this.dialogForm,
          })
            .then((response) => {
              this.canSave = false
              if (!response.data.hasError) {
                this.$message({
                  type: 'success',
                  message: '保存成功',
                })
                this.dialogVisible = false
                this.$refs.pagination.getTableListData()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.errorMsg,
                })
              }
            })
            .catch((error) => {})
        } else {
          return false
        }
      })
    },
    //日常、专项tab 选中问题
    tabChoose() {
      var oldUrl =
        this.taskType == 'SPECIAL'
          ? '/home/patrol/patrolListSpecial'
          : '/home/patrol/patrolList'
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: oldUrl,
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 246

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getApi() {
      if (localStorage.getItem('judgeRoleCode') === 'company') {
        if (this.taskType == 'SPECIAL') {
          this.api = 'api-s/report/export_JC_NC_SPECIAL_COMPANY_PATROL'
        } else {
          this.api = 'api-s/report/export_JC_NC_DAILY_COMPANY_PATROL'
        }
      } else {
        if (this.taskType == 'SPECIAL') {
          this.api = 'api-s/report/export_JC_CS_SPECIAL_COMPANY_PATROL'
        } else {
          this.api = 'api-s/report/export_JC_CS_DAILY_COMPANY_PATROL'
        }
      }
    },
  },
}
</script>

<style scoped lang="less">
.selectWidth {
  width: 100%;
}
@import '../../../static/css/filterArea.less';
</style>
